package com.lcq.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.lcq.common.enume.OrderStatusEnum;
import com.lcq.common.exception.WareOutOfStockException;
import com.lcq.common.to.OrderItemLockTo;
import com.lcq.common.to.OrderTo;
import com.lcq.common.to.StockDetailTo;
import com.lcq.common.to.StockLockedTo;
import com.lcq.common.utils.R;
import com.lcq.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.lcq.gulimall.ware.entity.WareOrderTaskEntity;
import com.lcq.gulimall.ware.feign.OrderFeignService;
import com.lcq.gulimall.ware.service.WareOrderTaskDetailService;
import com.lcq.gulimall.ware.service.WareOrderTaskService;
import com.lcq.gulimall.ware.vo.SkuStockVo;
import com.lcq.gulimall.ware.vo.WareSkuLockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcq.common.utils.PageUtils;
import com.lcq.common.utils.Query;

import com.lcq.gulimall.ware.dao.WareSkuDao;
import com.lcq.gulimall.ware.entity.WareSkuEntity;
import com.lcq.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
@Slf4j
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void add(Long skuId, Long wareId, Integer skuNum) {
        WareSkuEntity entity = this.getOne(new QueryWrapper<WareSkuEntity>().eq("sku_id",skuId).and((wrapper)->{
            wrapper.eq("ware_id",wareId);
        }));
        if(entity==null){
            entity = new WareSkuEntity();
            entity.setSkuId(skuId);
            entity.setWareId(wareId);
            entity.setStock(skuNum);
            entity.setStockLocked(0);
            this.save(entity);
        }else {
            entity.setStock(entity.getStock()+skuNum);
            this.updateById(entity);
        }
    }

    @Override
    public Boolean hasStock(Long skuId) {
        List<WareSkuEntity> list = this.getBaseMapper().selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId));
        if(list==null||list.size()==0){
            return false;
        }
        for (WareSkuEntity wareSkuEntity : list) {
            if(wareSkuEntity.getStock()-wareSkuEntity.getStockLocked()>0){
                return true;
            }
        }
        return false;
    }

    @Override
    public List<SkuStockVo> hasStocks(List<Long> skuIds) {
        return this.getBaseMapper().hasStocks(skuIds);
    }

    @Override
    @Transactional
    public void lockWare(WareSkuLockVo wareSkuLockVo) {
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        wareOrderTaskService.save(wareOrderTaskEntity);

        List<OrderItemLockTo> lockTos = wareSkuLockVo.getLocks();
        for (OrderItemLockTo lockTo : lockTos) {
            List<WareSkuEntity> list = this.getBaseMapper().getAppropriateWare(lockTo.getSkuId(),lockTo.getQuantity());
            if (list==null||list.size()==0){
                throw new WareOutOfStockException();
            }
//            int count = this.getBaseMapper().lockWare(lockTo.getSkuId(),lockTo.getQuantity());
//            if (count==0){
//
//            }

            /**
             * 默认选择第一个作为发货仓库
             */
            WareSkuEntity ware = list.get(0);
            ware.setStockLocked(ware.getStockLocked()+lockTo.getQuantity());
            this.updateById(ware);

            WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
            detailEntity.setTaskId(wareOrderTaskEntity.getId());
            detailEntity.setSkuId(lockTo.getSkuId());
            detailEntity.setSkuNum(lockTo.getQuantity());
            detailEntity.setWareId(ware.getWareId());
            detailEntity.setLockStatus(1);
            wareOrderTaskDetailService.save(detailEntity);

            StockLockedTo lockedTo = new StockLockedTo();
            StockDetailTo stockDetailTo = new StockDetailTo();
            BeanUtils.copyProperties(detailEntity,stockDetailTo);
            lockedTo.setId(wareOrderTaskEntity.getId());
            lockedTo.setDetailTo(stockDetailTo);
            /**
             * 锁定库存的消息发送到延时队列，此时不能保证数据一致性，一段时间后进行数据一致性处理
             */
            rabbitTemplate.convertAndSend("stock-event-exchange","stock.delay.queue",lockedTo);
        }
    }

    /**
     * 解锁库存
     */

    public void releaseLockWare(StockLockedTo lockedTo){
        Long taskId = lockedTo.getId();
        WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(taskId);
        if (taskEntity==null){
            /**
             * 事务已经回退了
             */
            return;
        }
        String orderSn = taskEntity.getOrderSn();

        R r = orderFeignService.getOrderBySn(orderSn);
        OrderTo orderTo = r.getData(new TypeReference<OrderTo>(){});
        if (orderTo==null){
            /**
             * 解锁库存
             */
            StockDetailTo detailTo = lockedTo.getDetailTo();
            Integer skuNum = detailTo.getSkuNum();
            Long wareId = detailTo.getWareId();
            Long skuId = detailTo.getSkuId();
            unlockStock(skuNum, wareId, skuId,detailTo.getId());
            log.info(">>>>>>>>>>>解锁库存>>>>>>>>>>");
        }

    }

    private void unlockStock(Integer skuNum, Long wareId, Long skuId,Long detailId) {
        WareSkuEntity wareSkuEntity = this.getOne(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).and((q) -> {
            q.eq("ware_id", wareId);
        }));
        wareSkuEntity.setStockLocked(wareSkuEntity.getStockLocked()-skuNum);
        this.updateById(wareSkuEntity);
        /**
         * 由于网络原因同一个消息可能收到多次，要修改遵循幂等性原则
         */
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(detailId);
        entity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(entity);
    }

    /**
     * 处理订单关闭消息
     * @param orderTo
     */
    @Override
    public void releaseLockWare(OrderTo orderTo) {
        if (!orderTo.getStatus().equals(OrderStatusEnum.CANCELED.getCode())){
            return;
        }
        WareOrderTaskEntity task = wareOrderTaskService.getOne(new QueryWrapper<WareOrderTaskEntity>()
                .eq("order_sn", orderTo.getOrderSn()));
        List<WareOrderTaskDetailEntity> wareOrderTaskDetailEntities = wareOrderTaskDetailService.getBaseMapper()
                .selectList(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", task.getId()).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : wareOrderTaskDetailEntities) {
            unlockStock(entity.getSkuNum(), entity.getWareId(), entity.getSkuId(),entity.getId());
            log.info(">>>>>>>>>>>解锁库存>>>>>>>>>>");
        }
    }
}